#include <Arduino.h>
// 本示例为公阳极数码管
// put function declarations here:
// 字码：0,1,2,3,4,5,6,7,8,9
const unsigned char segments[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
// 段位：a,b,c,d,e,f,g,dp
int seg_pins[] = {9, 13, 4, 6, 7, 10, 3, 5};
// 数位：1,2,3,4
int digit_pins[] = {2, 12, 11, 8};
int digit_vals[] = {0, 0, 0, 0};
// 位数
int digit_num = 4;
// 段数
int seg_num = 8;
// 字数
int char_num = 10;
// 当前计时值
int num = 0;
// 上次更新时间
unsigned long last_time;

void setup()
{
  // put your setup code here, to run once:
  for (int i = 0; i < digit_num; i++)
  {
    pinMode(digit_pins[i], OUTPUT);
    digitalWrite(digit_pins[i], LOW);
  }
  for (int i = 0; i < seg_num; i++)
  {
    pinMode(seg_pins[i], OUTPUT);
    digitalWrite(seg_pins[i], HIGH);
  }
}

void loop()
{
  // put your main code here, to run repeatedly:
  // 逐灯测试
  // for (int i = 0; i < digit_num; i++)
  // {
  //   digitalWrite(digit_pins[i], HIGH);
  //   for (int j = 0; j < seg_num; j++)
  //   {
  //     digitalWrite(seg_pins[j], LOW);
  //     delay(200);
  //     digitalWrite(seg_pins[j], HIGH);
  //   }
  //   digitalWrite(digit_pins[i], LOW);
  // }

  // 显示一位数字
  // for (int digit = 0; digit < digit_num; digit++)
  // {
  //   for (int i = 0; i < char_num; i++)
  //   {
  //     for (int j = 0; j < seg_num; j++)
  //     {
  //       digitalWrite(seg_pins[j], bitRead(segments[i], j) == 0);
  //     }
  //   }
  //   digitalWrite(digit_pins[digit], HIGH);
  //   delay(400);
  //   digitalWrite(digit_pins[digit], LOW);
  // }

  // 计数测试
  // num = 1234;
  int num_tmp = num;

  if (num_tmp > 999)
  {
    digit_vals[3] = num_tmp / 1000;
    num_tmp = num_tmp % 1000;
  }
  else
  {
    digit_vals[3] = 0;
  }

  if (num_tmp > 99)
  {
    digit_vals[2] = num_tmp / 100;
    num_tmp = num_tmp % 100;
  }
  else
  {
    digit_vals[2] = 0;
  }
  if (num_tmp > 9)
  {
    digit_vals[1] = num_tmp / 10;
    num_tmp = num_tmp % 10;
  }
  else
  {
    digit_vals[1] = 0;
  }
  digit_vals[0] = num_tmp;

  for (int digit = 0; digit < digit_num; digit++)
  {
    int n = digit_vals[digit];
    n = segments[n];
    for (int seg = 0; seg < seg_num; seg++)
    {
      digitalWrite(seg_pins[seg], bitRead(n, seg) == LOW);
    }
    digitalWrite(digit_pins[digit], HIGH);
    delay(1);
    digitalWrite(digit_pins[digit], LOW);
  }

  if (millis() - last_time >= 1000)
  {
    last_time = millis();
    if (num >= 9999)
    {
      num = 0;
    }
    else
    {
      num++;
    }
  }
}

// put function definitions here: